/**
 * Copyright (c) 2015-2020, wss 王山山
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wss.utils.scan;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiPredicate;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

/**
 * 扫描jar文件中指定包下的类文件
 * 
 * @author wss
 *
 */
class JarScanClasses implements ScanClasses {
	
	@Override
	public List<String> scanPackage(String filePath, String packageName) {
		return doScan(filePath, packageName, (e, v) -> isCurrentPackageClass(e, v));
	}
	
	@Override
	public List<String> scanPackageRecursive(String filePath, String packageName) {
		return doScan(filePath, packageName, null);
	}
	
	/*
	 * 扫描指定包下的类
	 */
	@SuppressWarnings("resource")
	private List<String> doScan(String filePath, String packageName, BiPredicate<String, String> isRecursive) {
		filePath = filePath.substring(ScanUtil.POSITION);
		List<String> classNames = new ArrayList<>();
		try {
			JarInputStream jarIn = new JarInputStream(new FileInputStream(filePath));
			JarEntry jarEntry = null;
			while ((jarEntry = jarIn.getNextJarEntry()) != null) {
				String name = jarEntry.getName();
				if (isTargetClassFile(packageName, name, isRecursive)) {
					String className = name.substring(0, name.indexOf(ScanUtil.CLASS_FILE_SUFFIX));
					classNames.add(className.replaceAll(ScanUtil.JAR_FILE_SEPARATOR, ScanUtil.DOT));
				}
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return classNames;
	}
	
	/*
	 * 判断是否是目标类
	 */
	private boolean isTargetClassFile(String packageName, String className, 
			BiPredicate<String, String> isRecursive) {
		
		boolean isClassFile = (className.startsWith(packageName) && isClassFile(className));
		return (isRecursive != null) 
				? (isClassFile && isRecursive.test(packageName, className)) 
				: isClassFile;
	}
	
	/*
	 * 判断类是否是包下的直接类
	 */
	private boolean isCurrentPackageClass(String packageName, String className) {
		int start = className.indexOf(packageName) + packageName.length() - 1;
		int end = className.lastIndexOf(ScanUtil.JAR_FILE_SEPARATOR);
		return (ScanUtil.POSITION_DISTANCE == end - start);
	}
}
